﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.EnterpriseServices;
using Webdiyer.WebControls.Mvc;
using YiYiTong.Rocket.Business;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.Model.Manager;
using System.Data;
using YiYiTong.Rocket.Helper;

namespace YiYiTong.Rocket.ManageWeb.Controllers
{
    public class ActionController : BaseController
    {
        #region 添加/修改功能
        [Description("添加/修改功能")]
        [ViewPage]
        public ActionResult AddAction(int ActionId = 0)
        {
            ActionInfo action = new ActionInfo();
            if (ActionId != 0)
            {
                ViewBag.Title = "修改功能";
                action = ActionBiz.Instance.GetActionInfoById(ActionId);
            }
            else
                ViewBag.Title = "添加功能";
            return View(action);
        }

        [Description("添加/修改功能")]
        [HttpPost]
        public ActionResult AddAction(ActionInfo actionReq)
        {
            int ret = 0;
            string strOutPut = string.Empty;
            ResponseMsg resMsg = new ResponseMsg();
            if (ModelState.IsValid)
            {
                if (actionReq.actionId == 0)
                {
                    //添加功能
                    ret = ActionBiz.Instance.AddAction(actionReq.actionName, actionReq.controllerName, actionReq.description, actionReq.remark, actionReq.parentId, out strOutPut);
                }
                else
                {
                    //修改功能
                    ret = ActionBiz.Instance.EditAction(actionReq.actionId, actionReq.actionName, actionReq.controllerName, actionReq.description, actionReq.remark, actionReq.parentId, out strOutPut);
                }
                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                resMsg.Message = strOutPut;
                resMsg.Body = Url.Action("ActionList", "Action");
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = ModelState.Values.First().Errors[0].ErrorMessage;
            }
            return Json(resMsg);
        }
        #endregion

        #region 列表显示父功能名称，新增\更新 Action新增父功能选择
        /// <summary>
        /// 返回下拉选择局部视图，返回具有层级结构的所有功能集合
        /// 选中参数parentId对应选项
        /// </summary>
        /// <param name="eleAttr">下拉框的元素信息（ID，Name，Class）</param>
        /// <param name="parentId">父功能Id</param>
        /// <returns></returns>
        [Description("功能下拉框")]
        [NoVerify]
        public ActionResult GetActionTreeDropList(ElementAttribute eleAttr, int parentId = 0)
        {
            ViewBag.EleAttr = eleAttr;
            ViewBag.ParentID = parentId;
            IList<ActionInfo> list = null;
            DataTable dt = ActionBiz.Instance.GetAllParentActionList();
            if (dt != null && dt.Rows.Count != 0)
            {
                //克隆原有数据表结构
                DataTable dtAction = dt.Clone();
                dtAction = Utils.GetDropItems(dt, dtAction, "Description", "ActionID", "0", "\u3000");
                list = new ModelHandler<ActionInfo>().FillModel(dtAction);
            }
            return PartialView(list);
        }

        /// <summary>
        /// 获得父功能描述名称
        /// </summary>
        /// <param name="parentID">父功能Id</param>
        /// <returns></returns>
        [Description("获取功能父级功能名称")]
        [NoVerify]
        public ActionResult GetParentActionDescription(int parentID)
        {
            if (parentID == 0)
                return Content("");
            var parentActionDes = ActionBiz.Instance.GetActionInfoById(parentID).description;
            return Content(parentActionDes);
        }
        #endregion

        #region 删除功能
        [Description("删除功能")]
        [HttpPost]
        public ActionResult DelAction(int ActionId = 0)
        {
            int ret = 0;
            string strOutPut = string.Empty;
            ResponseMsg resMsg = new ResponseMsg();
            resMsg.Body = Url.Action("ActionList", "Action");
            if (ActionId != 0)
            {
                ret = ActionBiz.Instance.DeleteAction(ActionId, out strOutPut);
                if (ret <= 0)
                {
                    resMsg.IsSuccess = false;
                    resMsg.Message = strOutPut;
                    return Json(resMsg, JsonRequestBehavior.AllowGet);
                }

                resMsg.Message = strOutPut;
            }
            else
            {
                resMsg.IsSuccess = false;
                resMsg.Message = "功能不存在";
                return Json(resMsg, JsonRequestBehavior.AllowGet);
            }
            return Json(resMsg);
        }
        #endregion

        #region 功能列表
        [Description("查询功能列表")]
        [ViewPage]
        public ActionResult ActionList(string actionName = "", string controllName = "", string description = "", string parentName = "", int pageIndex = 1, int pageSize = 10)
        {
            var ds = ActionBiz.Instance.GetPageList(actionName, controllName, description, parentName, pageIndex, pageSize);
            var allrows = ConvertHelper.ConvertTo<int>(ds.GetTable(0).Rows[0]["allrows"], 0);
            IList<ActionInfo> list = new ModelHandler<ActionInfo>().FillModel(ds, 1);
            PagedList<ActionInfo> pagedlist = null;
            if (list != null && list.Count != 0)
                pagedlist = new PagedList<ActionInfo>(list, pageIndex, pageSize, allrows);
            return View(pagedlist);
        }
        #endregion

        #region 功能checkbox列表 NoVerify
        [Description("功能checkbox列表")]
        [NoVerify]
        public PartialViewResult CheckBoxActionList(ElementAttribute EleAttr)
        {
            ViewBag.EleAttr = EleAttr;
            DataTable dt = ActionBiz.Instance.GetAllActionList();
            IList<ActionInfo> list = null;
            if (dt != null && dt.Rows.Count != 0)
            {
                DataView dv = dt.DefaultView;
                dv.Sort = "Controllname asc";

                DataTable dtaction = dv.ToTable();
                list = new ModelHandler<ActionInfo>().FillModel(dtaction);
            }
            return PartialView(list);
        }
        #endregion

        #region 功能树状菜单
        /// <summary>
        /// 获得具有层级结构的Action的集合Json格式
        /// </summary>
        /// <returns></returns>
        [Description("功能树状菜单checkbox列表")]
        [NoVerify]
        public string GetChxBoxActionList(int roleId)
        {
            //获得所有Action集合
            DataTable allActionDt = ActionBiz.Instance.GetAllActionList();
            List<ActionInfo> actionList = new ModelHandler<ActionInfo>().FillModel(allActionDt);
            //获得当前用户Action权限
            DataTable roleActionDt = RoleBiz.Instance.GetRoleActionList(roleId);
            List<ActionTree> treeList = new List<ActionTree>();
            FillActionTree(actionList, treeList, null, roleActionDt, 0);
            return JsonHelper.Serialize(treeList).Replace("m_checked", "checked");
        }

        /// <summary>
        /// 递归 填充treeList集合
        /// treeList具有层级结构
        /// </summary>
        /// <param name="actionList">所有功能集合</param>
        /// <param name="treeList">需要填充的ActionTree集合</param>
        /// <param name="tree">ActionTree对象，向该对象中添加子节点</param>
        /// <param name="roleActionDt">当前角色拥有的Action集合</param>
        /// <param name="parentCode">父级节点ID</param>
        private void FillActionTree(List<ActionInfo> actionList, List<ActionTree> treeList, ActionTree tree, DataTable roleActionDt, int parentCode)
        {
            var childActionList = actionList.FindAll(p => p.parentId == parentCode);
            if (childActionList.Count > 0)
            {
                foreach (var action in childActionList)
                {
                    ActionTree tr = GetActionTree(action, roleActionDt);
                    FillActionTree(actionList, treeList, tr, roleActionDt, action.actionId);
                    //tree为null时，即第一层循环，否则为进入子集递归循环过程
                    if (tree == null)
                        treeList.Add(tr);
                    else
                        tree.children.Add(tr);
                }
            }
        }

        /// <summary>
        /// 根据传入的功能实体和当前用户拥有的功能
        /// 返回功能树实体
        /// </summary>
        /// <param name="action">Action实体</param>
        /// <param name="roleActionDt">用户拥有功能</param>
        /// <returns></returns>
        private ActionTree GetActionTree(ActionInfo action, DataTable roleActionDt)
        {
            ActionTree tr = new ActionTree();
            tr.id = action.actionId.ToString();
            tr.text = action.description;
            tr.m_checked = IsCheckedUserHaveAction(action.actionId, roleActionDt);
            return tr;
        }

        /// <summary>
        /// 返回当前用户是否拥有该功能
        /// 拥有返回True，否则False
        /// </summary>
        /// <param name="actionId">功能id</param>
        /// <param name="roleActionDt">当前用户拥有功能列表</param>
        /// <returns></returns>
        private bool IsCheckedUserHaveAction(int actionId, DataTable roleActionDt)
        {
            if (roleActionDt != null && roleActionDt.Rows.Count > 0)
            {
                string strFilter = string.Format("ActionID={0}", actionId);
                DataRow[] drs = roleActionDt.Select(strFilter);
                return (drs != null && drs.Length != 0);
            }
            return false;
        }
        #endregion
    }
}